package com.waijiaojun.tpo.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.waijiaojun.tpo.exception.ServerException;

public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static void main(String[] args) {

    }

    /**
     * 读取微信素图片资源
     *
     * @param url
     * @param body
     * @param imageFilePathname 需要保存的文件名（包含路径和名称，如路径不存在自动创建相应的目录）
     * @param isScalr           是否缩放图片（120 x 120）
     * @throws IOException
     * @throws ClientProtocolException
     * @throws Exception
     */
    public static void httpPostForMedia(String url, String body, String imageFilePathname, boolean isScalr) throws ClientProtocolException, IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(url);

            if (StringUtils.isNoneBlank(body)) {
                StringEntity myEntity = new StringEntity(body, ContentType.create("text/plain", "UTF-8"));
                post.setEntity(myEntity);
            }

            logger.info("Executing request " + post.getRequestLine() + "  \n  body----->>" + body);
            CloseableHttpResponse response = httpclient.execute(post);
            logger.info("Executed response " + response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream responseBody = entity.getContent();

                File f = new File(imageFilePathname);
//				f.mkdirs();
                if (isScalr) {
                    //缩放图片
                    BufferedImage thumbnail = Scalr.resize(ImageIO.read(responseBody), Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 120, 120, Scalr.OP_ANTIALIAS);// 生成缩略图
                    ImageIO.write(thumbnail, "png", f);
                } else {
                    ImageIO.write(ImageIO.read(responseBody), "png", f);
                }
                logger.info("创建图片：" + imageFilePathname);
            } else {
                logger.error("读取微信素图片资源：没有任何图片资源，entity is null!");
            }
        } catch (Exception e) {
            logger.error("读取微信素图片资源Error", e);
            throw new ServerException("读取微信素图片资源Error");
        }
    }

    /**
     * http post 请求
     *
     * @param url
     * @param body
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String httpPost(String url, String body) throws IOException {
        String responseBody = "";

        CloseableHttpResponse response;
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(url);
            StringEntity myEntity = new StringEntity(body, ContentType.create("text/plain", "UTF-8"));
            post.setEntity(myEntity);

            logger.info("Executing request " + post.getRequestLine() + "  \n  request body----->>\n" + body);
            response = httpclient.execute(post);
            logger.info("Executed response " + response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseBody = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            logger.error("http 请求失败", e);
            throw new ServerException("http 请求失败");
        }
        logger.info("Executed response body----->>\n" + responseBody);
        return responseBody;
    }

    public static String httpGet(String url) {
        String body = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {

            HttpGet httpget = new HttpGet(url);

            logger.info("Executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                logger.info(response.getStatusLine().toString());

                // Get hold of the response entity
                HttpEntity entity = response.getEntity();

                // If the response does not enclose an entity, there is no need
                // to bother about connection release
                if (entity != null) {
                    body = EntityUtils.toString(entity, "utf-8");
                    logger.info(body);
                }

            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("http 请求失败");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("http 请求失败");
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return body;
    }

    public static String getTDCode(String ticket,String openid) {
        logger.info("----------------------------------------\n--- 第二步：openid=" + openid);
        String TICKET = null;
        String path = null;
        try {
            TICKET = URLEncoder.encode(ticket, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + TICKET;
            HttpGet httpGet = new HttpGet(url);
            logger.info("Executing request " + httpGet.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpGet);
            logger.info("Executed response " + response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream responseBody = entity.getContent();
                Long size = entity.getContentLength();
                path = AliyunOssUtil.uploadQRCode(responseBody,openid,size);

                logger.info("上传二维码到OSS成功：" +path);
            } else {
                logger.error("创建微信带场景值二维码失败，http请求错误，entity is null!");
            }
        } catch (Exception e) {
            logger.error("创建微信带场景值二维码Error", e);
            throw new ServerException("创建二维码Error");
        }

        return path;
    }
}
